<template>
  <base-modal
    :show.sync="visible"
    :title="$t('smartPlan.createPlan')"
    class="create-smart-plan-modal"
    width="500px"
    @cancel="close"
  >
    <el-form
      ref="form"
      class="form-container"
      :rules="rules"
      label-position="top"
      :model="form"
    >
      <el-form-item :label="$t('task.edit.planName')" prop="planName">
        <el-input v-model="form.planName" :placeholder="t('common.placeholder.inputSomething', {data1: t('task.edit.planName')})"></el-input>
      </el-form-item>
      <el-form-item :label="$t('smartPlan.businessObj')" prop="planType">
        <div class="business-obj-wrap">
          <base-select-app v-if="visible" @select="selectApp" @showPaasTip="showPaasTip"></base-select-app>
        </div>
        <div class="business-list-tip flex-x" v-if="visible && showTip">
          <i class="iconfont icon-info"></i> <span class="mar-l-5">{{ $t('smartPlan.tips.tip8') }}</span>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="close">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :loading="loading">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import { openAccurateTab } from '@src/util/platform'
import { checkPlanName, getTriggerFieldList } from '@src/modules/smartPlan/api/index.js'
import { t } from '@src/locales'
import _ from 'lodash'
export default {
  name: 'create-smart-plan-modal',
  props: {
    customers: {
      type: Array,
      default: () => ([])
    },
    products: {
      type: Array,
      default: () => ([])
    },
  },
  data() {
    return {
      visible: false,
      showTip: false,
      loading: false,
      form: {
        planName: '', // 计划类型 TASK:工单 EVENT：事件 PAAS：paas
        planType: '',
        planTypeId: '',
        planTypeName: '',
      },
      rules: {
        planName: [
          { required: true, message: t('common.placeholder.inputSomething', {data1: t('task.edit.planName')}), trigger: 'blur' },
          { max: 50, message: t('common.validate.nameLimit', {limit: 50}), trigger: 'blur' },
          { validator: this.checkName, trigger: ['blur', 'change'] },
        ],
        planType: [
          { required: true, message: t('common.placeholder.selectSomething', {0: t('smartPlan.businessObj')}), trigger: 'blur' },
        ]
      }
    }
  },
  methods: {
    open() {
      this.visible = true
      this.$refs.form.clearValidate()
    },
    close() {
      this.form.planName = ''
      this.form.planType = ''
      this.form.planTypeId = ''
      this.form.planTypeName = ''
      this.visible = false
    },
    checkName: _.debounce(function(rule, value, callback) {
      if (!value) return callback()
      checkPlanName({planName: value}).then(result => {
        if (!result.succ) {
          callback(new Error(result.message))
        } 
        callback()
      })
    }, 1000),
    selectApp(data) {
      this.form.planType = data.type
      this.form.planTypeId = data.formId
      this.form.planTypeName = data.name
      this.$refs.form.clearValidate(['planType'])
    },
    showPaasTip(data) {
      this.showTip = data
    },
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 缓存数据，跳转新建智能计划页面
          const data = _.cloneDeep(this.form)
          // customers有数据说明是从客户那边跳转过来的
          data.customers = this.customers || []
          // products有数据说明是从产品那边跳转过来的
          data.products = this.products || []
          // 校验业务对象表单字段是否包含客户或者产品
          if (data.customers.length || data.products.length) {
            this.loading = true
            const res = await getTriggerFieldList({ bizType: this.form.planType, formId: this.form.planTypeId })
            this.loading = false
            const fields = res.data || []
            if (data.customers.length) {
              const customerField = fields.find(f => f.formType == 'customer')
              if (!customerField) {
                return this.$platform.alert(t('smartPlan.tips.tip9'))
              }
            } else {
              const productField = fields.find(f => f.formType == 'product')
              if (!productField) {
                return this.$platform.alert(t('smartPlan.tips.tip10'))
              }
            }
          } 
          localStorage.setItem('createSmartPlanData', JSON.stringify(data))
          let fromId = window.frameElement?.getAttribute('id');
          openAccurateTab({
            type: PageRoutesTypeEnum.PageSmartPlanCreate,
            params:`planName=${this.form.planName}&planTypeId=${this.form.planTypeId}`,
            fromId
          })
          this.close()
        }
      });
    }
  }
}
</script>

<style lang="scss">
.create-smart-plan-modal {
  .form-container {
    .el-input input {
      border: 1px solid #CBD6E2;
    }
    .business-obj-wrap {
      padding: 12px;
      border-radius: 4px;
      border: 1px solid #CBD6E2;
    }
    .business-list-tip {
      height: 28px;
      .iconfont {
        color: #8C8C8C;;
      }
      span {
        font-size: 12px;
        color: #3D3D3D;
      }
    }
  }
  .base-modal-body {
    padding: 24px!important;
  }
}
</style>